package com.felix.ocoupon.serialization;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.felix.ocoupon.entity.OcouponTemplate;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author hsufelix
 * @email hsufelix@yeah.net
 * @Date 2020/11/12
 */
public class OcouponTemplateSerialize extends JsonSerializer<OcouponTemplate> {


    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     */
    @Override
    public void serialize(OcouponTemplate value,
                          JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        gen.writeStartObject();

        gen.writeStringField("id", value.getId().toString());
        gen.writeStringField("name", value.getName());
        gen.writeStringField("logo", value.getLogo());
        gen.writeStringField("desc", value.getDescription());
        gen.writeStringField("category", value.getCategory().getDescription());
        gen.writeStringField("productLine", value.getProductLine().getDescription());
        gen.writeStringField("counts", value.getCounts().toString());
        final String ct =
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value.getCreateTime());
        gen.writeStringField("createTime", ct);
        gen.writeStringField("userId", value.getUserId().toString());
        gen.writeStringField("key",
                value.getKey() + String.format("%04d") + value.getId());
        gen.writeStringField("target", value.getTarget().getDescription());
        gen.writeStringField("rule",
                JSON.toJSONString(value.getRule()));

        gen.writeEndObject();
    }
}
